<template>
  <div>
    <div class="header">
      <div class="title">{{ title }}</div>
      <div class="right">
        <el-button size="small" type="primary" @click="print()">打印</el-button>
      </div>
    </div>
    <div id="luckysheet"></div>
  </div>
</template>

<script setup>
import axios from "axios";

const title = ref("文件标题");

/**
 * 获取excel文档
 */
async function getDoc() {
  const res = await axios({
    url: "http://localhost:8000/order.xlsx",
    method: "get",
    responseType: "blob",
  });
  const file = blobToFile(res.data, "order");
  initExcel(file);
}

getDoc();

function blobToFile(blob, name) {
  return new File([blob], name);
}

function initExcel(file) {
  window.LuckyExcel.transformExcelToLucky(file, function (exportJson, luckysheetfile) {
    if (exportJson.sheets === null || exportJson.sheets.length === 0) {
      alert("Failed to read the content of the excel file, currently does not support xls files!");
      $message.error("文件加载失败");
      return;
    }
    window.luckysheet.destroy();
    window.luckysheet.create({
      container: "luckysheet",
      allowEdit: true,
      data: exportJson.sheets,
      lang: "zh",
      title: "订单20241201",
      addRowCount: 100,
      myFolderUrl: "/",
      showinfobar: false,
    });
  });
}

onUnmounted(() => {
  window.luckysheet.destroy();
});

function print() {
  document.querySelector("#luckysheet-left-top").click();
  const selectHtml = window.luckysheet.getRangeHtml();
  // 创建一个临时窗口或 iframe
  const printWindow = window.open("", "_blank"); // 使用空 URL 打开新窗口
  // 将 HTML 内容插入临时窗口或 iframe
  printWindow.document.write(selectHtml);
  printWindow.document.close();
  // 调用打印功能
  printWindow.print();
}
</script>

<style scoped lang="scss">
.header {
  height: 45px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;

  .title {
    font-size: 16px;
    font-weight: bold;
  }
}

#luckysheet {
  width: 100%;
  height: calc(100vh - 45px);
}
</style>
